import {createRouter, createWebHistory} from 'vue-router'

// 客户端路由 - 无需登录即可访问
const clientRoutes = [
    {
        path: '/faceQueue',
        name: 'FaceQueue',
        component: () => import('../views/client/FaceQueue.vue'),
        meta: { requiresAuth: false, title: '自助取号' }
    },
    {
        path: '/faceVerify',
        name: 'FaceVerify',
        component: () => import('../views/client/FaceVerify.vue'),
        meta: { requiresAuth: false, title: '人脸验证' }
    },
    {
        path: '/callScreen',
        name: 'CallScreen',
        component: () => import('../views/client/CallScreen.vue'),
        meta: { requiresAuth: false, title: '呼叫显示屏' }
    },
    {
        path: '/callTerminal',
        name: 'CallTerminal',
        component: () => import('../views/client/CallTerminal.vue'),
        meta: { requiresAuth: true, title: '窗口叫号终端', roles: ['operator', 'admin', 'superadmin'] }
    }
]

// 管理后台路由 - 需要登录才能访问
const adminRoutes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Login.vue'),
        meta: { requiresAuth: false, title: '登录' }
    },
    {
        path: '/',
        component: () => import('../views/Layout.vue'),
        redirect: '/dashboard',
        meta: { requiresAuth: true },
        children: [
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: () => import('../views/Dashboard.vue'),
                meta: { title: '数据大盘', icon: 'DataLine', roles: ['admin', 'superadmin'] }
            },
            {
                path: 'queue',
                name: 'QueueManagement',
                component: () => import('../views/queue/Index.vue'),
                meta: { title: '队列管理', icon: 'List', roles: ['admin', 'superadmin'] },
                redirect: '/queue/list',
                children: [
                    {
                        path: 'list',
                        name: 'QueueList',
                        component: () => import('../views/queue/QueueList.vue'),
                        meta: { title: '队列列表', roles: ['admin', 'superadmin'] }
                    },
                    {
                        path: 'window',
                        name: 'WindowManagement',
                        component: () => import('../views/queue/WindowManagement.vue'),
                        meta: { title: '窗口管理', roles: ['admin', 'superadmin'] }
                    }
                ]
            },
            {
                path: 'business',
                name: 'BusinessManagement',
                component: () => import('../views/business/Index.vue'),
                meta: { title: '业务管理', icon: 'Briefcase', roles: ['admin', 'superadmin'] },
                redirect: '/business/type',
                children: [
                    {
                        path: 'type',
                        name: 'BusinessType',
                        component: () => import('../views/business/BusinessType.vue'),
                        meta: { title: '业务类型', roles: ['admin', 'superadmin'] }
                    }
                ]
            },
            {
                path: 'statistics',
                name: 'Statistics',
                component: () => import('../views/statistics/Index.vue'),
                meta: { title: '业务统计', icon: 'PieChart', roles: ['admin', 'superadmin'] },
                redirect: '/statistics/daily',
                children: [
                    {
                        path: 'daily',
                        name: 'DailyStatistics',
                        component: () => import('../views/statistics/DailyStatistics.vue'),
                        meta: { title: '日常统计', roles: ['admin', 'superadmin'] }
                    },
                    {
                        path: 'report',
                        name: 'StatisticsReport',
                        component: () => import('../views/statistics/StatisticsReport.vue'),
                        meta: { title: '统计报表', roles: ['admin', 'superadmin'] }
                    }
                ]
            },
            {
                path: 'system',
                name: 'SystemManagement',
                component: () => import('../views/system/Index.vue'),
                meta: { title: '系统管理', icon: 'Setting', roles: ['admin', 'superadmin'] },
                redirect: '/system/user',
                children: [
                    {
                        path: 'user',
                        name: 'UserManagement',
                        component: () => import('../views/system/UserManagement.vue'),
                        meta: { title: '用户管理', roles: ['superadmin'] }
                    },
                    {
                        path: 'role',
                        name: 'RoleManagement',
                        component: () => import('../views/system/RoleManagement.vue'),
                        meta: { title: '角色管理', roles: ['superadmin'] }
                    },
                    {
                        path: 'config',
                        name: 'SystemConfig',
                        component: () => import('../views/system/SystemConfig.vue'),
                        meta: { title: '系统配置', roles: ['admin', 'superadmin'] }
                    }
                ]
            }
        ]
    }
]

// 404路由
const notFoundRoute = {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
    meta: { requiresAuth: false, title: '页面未找到' }
}

// 合并所有路由
const routes = [
    ...clientRoutes,
    ...adminRoutes,
    {
        // 将根路径默认重定向到自助取号页面
        path: '/',
        redirect: '/faceQueue'
    },
    notFoundRoute
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    // 设置页面标题
    document.title = to.meta.title || '排队叫号系统'

    // 获取用户信息
    const token = localStorage.getItem('token')
    const userInfoStr = localStorage.getItem('userInfo')
    let userInfo = null

    if (userInfoStr) {
        try {
            userInfo = JSON.parse(userInfoStr)
        } catch (e) {
            console.error('Parse userInfo error:', e)
        }
    }

    // 无需权限的页面直接通过
    if (!to.meta.requiresAuth) {
        // 已登录用户访问登录页，重定向到相应页面
        if (to.path === '/login' && token && userInfo) {
            if (userInfo.role === 'operator') {
                return next('/callTerminal')
            } else {
                return next('/dashboard')
            }
        }
        return next()
    }

    // 需要权限但未登录
    if (!token || !userInfo) {
        // 排除取号页、人脸验证页和呼叫大屏页面，这些页面不需要登录
        if (to.path === '/faceQueue' || to.path === '/faceVerify' || to.path === '/callScreen') {
            return next()
        }
        return next({ name: 'Login', query: { redirect: to.fullPath } })
    }

    // 检查角色权限
    const { role } = userInfo
    const allowedRoles = to.meta.roles

    if (allowedRoles && !allowedRoles.includes(role)) {
        // 没有权限，重定向到相应页面
        if (role === 'operator') {
            return next('/callTerminal')
        } else if (role === 'admin') {
            return next('/dashboard')
        } else {
            return next('/dashboard')
        }
    }

    // 有权限，允许访问
    next()
})

export default router
